<?php
/**
 * Created by PhpStorm.
 * User: lvyinhong
 * Date: 2019-03-10
 * Time: 19:36
 */

namespace App\Models\Traits;


use App\Models\CollectionApiRequest;
use App\Models\RepayRecord;
use phpDocumentor\Reflection\Types\Self_;

/**
 * 商户代偿（销帐）功能 trait 包
 * Trait PayCompensate
 * @package App\Models\Traits
 */
trait PayCompensate
{

    protected $errors = [
        1000 => '该还款正在销账中',
        1001 => '还一期时，期数只能是一个大于0值',
        1002 => '还款期数有误, 请核对',
        1003 => '该期已还清，请核对参数',
        1004 => '该还款还在销账中',
        1005 => '还款不足',
        1006 => '还多期时，期数之间用逗号隔开',
        1007 => '当前没有还款计划',
        1008 => '有已还清的期数，请核对参数',
        1009 => '还款不足，有销账失败的期数请核对',
        1010 => '全部销账功能暂时不能实现',
        1011 => '该接口不在开放时间',
        1012 => '还款信息不存在, 请核对参数',
    ];

    protected $errorInfo = null;

    protected function setError($errCode, array $array = [])
    {
       $this->errorInfo = isset($this->errors[$errCode])?vsprintf($this->errors[$errCode], $array):false;
       return $this->errorInfo;
    }

    public function getError()
    {
        return $this->errorInfo === null ? false : $this->errorInfo;
    }

    /**
     * 验证是否是开启时间段
     *
     * @return bool
     */
    public function canUsePayCompensate()
    {
        $enable = env('PAY_COMPENSATE_ENABLE', false);
        if($enable) {
            return true;
        }
        $beginString = env('PAY_COMPENSATE_BEGIN');
        $endString = env('PAY_COMPENSATE_END');
        $beginTime = strtotime(date('Y-m-d '). $beginString);
        $endTime = strtotime(date('Y-m-d '). $endString);
        $time = time();
        if($time > $beginTime && $time < $endTime) {
            return true;

        }
        $this->setError(1011);
        return false;
    }

    public function verifyParams($repayAmount, $periods, $type)
    {
        $hadMoney = $repayAmount;
        $hadMoneyFen = $hadMoney * 100;
        $records = [];
        switch ($type) {
            case CollectionApiRequest::WRITEOFF_ONE:
                if($periods < 1) {
                     $this->setError(1001);
                     return false;
                }
                if($periods > $this->period_count) {
                     $this->setError(1002);
                     return false;
                }
                foreach ($this->recordMany as $record) {
                    if($record->period == $periods) {
                        if($record->status == RepayRecord::STATUS_FOUR) {
                            $this->setError(1003);
                            return false;
                        }
                        // 该还款正在销账中
                        if($this->isPayCompensating($record)) {
                            $this->setError(1004);
                            return false;
                        }
                        // 有记录,说明该期不是提前结清的。只能还一期。
                        $needMoney = \App\Models\RepaySummary::getRepayMoney($record)['all_money'];
                        if($hadMoneyFen < $needMoney) {
                            // 将 $hadMoney 存入repay_records.balance 中
                            $record->balance += $hadMoneyFen;
                            $record->save();
                            $this->setError(1005);
                            return false;
                        }
                        $records[] = $record;
                    }
                }
            break;
            case CollectionApiRequest::WRITEOFF_TWO:
                if(!is_array($periods)) {
                    $this->setError(1006);
                    return false;
                }
                if(!count($this->recordMany)) {
                    $this->setError(1007);
                    return false;
                }

                foreach ($this->recordMany as $record) {
                    if(in_array($record->period, $periods)) {
                        if($record->status === RepayRecord::STATUS_FOUR) {
                            $this->setError(1008);
                            return false;
                        }
                        // 有记录,说明该期不是提前结清的。只能还多期(逾期)。
                        $needMoney = \App\Models\RepaySummary::getRepayMoney($record)['all_money'];
                        if($hadMoneyFen < $needMoney) {
                            // 将 $hadMoney 存入repay_records.balance 中
                            $record->balance += $hadMoneyFen;
                            $record->repay_type = RepayRecord::REPAY_TYPE_ACCOUNT;
                            $record->save();
                            $this->setError(1009);
                            return false;
                        }
                        $hadMoneyFen -= $needMoney;
                        $records[] = $record;
                    }
                }
                break;
            case CollectionApiRequest::WRITEOFF_ZERO:
                $this->setError(1010);
                return false;
                break;

        }

        return $records;
    }

    /**
     * 正在销账为成功，所以设置为1000
     *
     * @return bool
     */
    public function setPayCompensating()
    {
        $this->setError(1000);
        return true;
    }

    /**
     * 是否正在销账中
     *
     * @param RepayRecord $record
     * @return bool
     */
    public function isPayCompensating(RepayRecord $record)
    {
        if(($record->status == RepayRecord::STATUS_TWO) && ($record->repay_type == RepayRecord::REPAY_TYPE_ACCOUNT)) {
            $this->setError(1004);
            return true;
        }
        return false;
    }

    /**
     * 销账是否已完成
     *
     * @param RepayRecord $record
     * @return bool
     */
    public function isPayCompensated(RepayRecord $record)
    {
        if(($record->status == RepayRecord::STATUS_FOUR) && ($record->repay_type == RepayRecord::REPAY_TYPE_ACCOUNT)) {
            return true;
        }
        return false;
    }
}